#include "socketrequesthandler.h"

SocketRequestHandler::SocketRequestHandler(QObject *parent)
    : QObject{parent}
{
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &SocketRequestHandler::handleResponse);
    connect(tcpSocket, &QTcpSocket::connected, this, &SocketRequestHandler::sendNextRequest);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &SocketRequestHandler::closeConnection);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &SocketRequestHandler::socketDisconnected);
}

SocketRequestHandler::~SocketRequestHandler()
{
    closeConnection();
}

void SocketRequestHandler::startProcessingRequests()
{
    for (const auto& str : stringArray) {
        pendingRequests.enqueue(str);
    }
    sendNextRequest();
}

void SocketRequestHandler::sendRequest(const QString& request)
{
    tcpSocket->write(request.toUtf8());
    tcpSocket->flush();
}

void SocketRequestHandler::handleResponse()
{
    QByteArray accumulatedData;
    while (tcpSocket->bytesAvailable()) {
        accumulatedData.append(tcpSocket->readAll());
    }

    emit resultReady(QString::fromUtf8(accumulatedData));
    sendNextRequest();
}

void SocketRequestHandler::sendNextRequest()
{
    if (!pendingRequests.isEmpty()) {
        QString nextRequest = pendingRequests.dequeue();
        sendRequest(nextRequest);
    } else {
        emit finished();
    }
}

void SocketRequestHandler::closeConnection()
{
    tcpSocket->disconnectFromHost();
    tcpSocket->deleteLater();
}
void SocketRequestHandler::socketDisconnected()
{
    emit finished();
}
